package com.yc.web.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import com.yc.tomcat.core.ConstantInfo;
import com.yc.tomcat.core.ParseXml;
import com.yc.tomcat.util.StringUtil;

public class HttpServletResponse implements ServletResponse{

	private OutputStream os = null;
	private String projectName; //工程名

	public HttpServletResponse(OutputStream os, String projectName) {
		this.os = os;
		this.projectName = projectName;
	}
	/**
	 * 获取输出流
	 * @return
	 * @throws IOException 
	 */
	@Override
	public PrintWriter getWriter()  {
		try {
			String responseHeader = "HTTP/1.1 200 OK\r\nContent-Type:text/html;charset=utf-8\r\n\r\n";
			os.write(responseHeader.getBytes());
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new PrintWriter(os);
	}

	/**
	 * 重定向
	 * @param url
	 */
	@Override
	public void sendRedirect(String url) {
		if(StringUtil.checkNull(url)) {
			error404(url);
			return;
		}
		
		if(!url.startsWith(projectName)) { //说明是动态资源里面的跳转
			url = projectName + "/" + url;
		}
		
		if(url.startsWith("/") && url.indexOf("/") == url.lastIndexOf("/")) { //说明请求方式是/项目名
			send302(url);
			return;
		}
		
		if(url.endsWith("/")) { //说明没有指定具体资源
			File fl = new File(ConstantInfo.BASE_PATH, url.substring(1).replace("/", "\\") + ConstantInfo.DEFAULT_RESOURCE);
			if(!fl.exists()) {
				error404(url);
				return;
			}
			send200(readFile(fl), ConstantInfo.DEFAULT_RESOURCE.substring(ConstantInfo.DEFAULT_RESOURCE.lastIndexOf(".") + 1).toLowerCase());
			return;
		}
		
		
		File fl = new File(ConstantInfo.BASE_PATH, url.substring(1).replace("/", "\\"));
		if(!fl.exists()) {
			error404(url);
			return;
		}

		send200(readFile(fl), url.substring(url.lastIndexOf(".") + 1).toLowerCase());
	}

	/**
	 * 读取指定文件
	 * @param fl
	 * @return
	 */
	private byte[] readFile(File fl) {
		byte[] bt = null;
		try(FileInputStream fis = new FileInputStream(fl)){
			bt = new byte[fis.available()];
			fis.read(bt);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bt;
	}

	/**
	 * 200响应
	 * @param bt
	 * @param extension
	 */
	private void send200(byte[] bt, String extension) {
		String contentType = "text/html;charset=utf-8";
		String temp = ParseXml.getContentType(extension);
		if(!StringUtil.checkNull(temp)) {
			contentType = temp;
		}

		try {
			String responseHeader = "HTTP/1.1 200 OK\r\nContent-Type:" + contentType + "\r\nContent-Length" + bt.length + "\r\n\r\n";
			os.write(responseHeader.getBytes());
			os.write(bt);
			os.flush();
		}catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 302
	 */
	private void send302(String url) {
		try {
			String responseHeader = "HTTP/1.1 302 File Move Temporarily\r\nContent-Type: text/html;charset=utf-8\r\nLocation:" + url + "/\r\n\r\n";
			os.write(responseHeader.getBytes());
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	/**
	 * 404
	 */
	private void error404(String url) {
		try {
			String data = "<h1>Htttp Status 404 - " + url + "<h1>";
			String responseHeader = "HTTP/1.1 404 File Not Found\r\nContent-Type: text/html;charset=url-8\r\nContenLength:" + data.getBytes().length + "\r\n\r\n";
			os.write(responseHeader.getBytes());
			os.write(data.getBytes());
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
